//
//  NSString+Weibo.m
//  MMBangADDemoProject
//
//  Created by CuiPanJun on 15-1-29.
//  Copyright (c) 2015年 CuiPanJun. All rights reserved.
//

#import "NSString+Weibo.h"

@implementation NSString (Weibo)

-(NSUInteger)charLength{
    
    NSUInteger length = 0;
    char *cStr = (char *)[self cStringUsingEncoding:NSUTF8StringEncoding];
    NSUInteger strBytesLength = [self lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
    unsigned char *p = (unsigned char*)cStr;
    for (int i=0 ; i<strBytesLength ;) {
        if(*p >= 0xF0 && *p < 0xF8){
            
            p += 4;
            i += 4;
            
            length ++;
            
        }else if (*p >= 0xE0 && *p < 0xF0) {
            
            p += 3;
            
            i += 3;
            
            length += 2;
            
        }
        
        else if(*p >= 0xB0 && *p < 0xF0) {
            
            p += 2;
            
            i += 2;
            
            length ++;
            
        }else{
            
            p += 1;
            
            i ++;
            
            length ++;
            
        }
        
    }
    
    return length;
}



NSUInteger charLength2WeiboLength(NSUInteger charLength);

-(NSUInteger)weiboLength{
    
    NSUInteger charLength = [self charLength];
    
    return charLength2WeiboLength(charLength);
    
}

NSUInteger charLength2WeiboLength(NSUInteger charLength){
    
    NSUInteger weiboLength = 0;
    
    if (charLength%2) {
        weiboLength = charLength/2 + 1;
    }else{
        weiboLength = charLength/2;
    }
    
    return weiboLength;
}


// 如何正确截取字符串

-(NSString *)substringToIndexForWeibo:(NSUInteger)index{
    
    NSUInteger unicodeCharLength = self.length;
    
    NSUInteger charLength = self.charLength;
    
    NSUInteger weiboLength = [self weiboLength];
    
    if (weiboLength < index) {
        
        return self;
        
    }else{
        
        NSMutableString *mutableStr = [NSMutableString stringWithString:self];
        
        while (weiboLength > index) {
            NSString *lastStr = [mutableStr substringFromIndex:unicodeCharLength-1];
            [mutableStr deleteCharactersInRange:NSMakeRange(unicodeCharLength-1, 1)];
            unicodeCharLength--;
            charLength -= [lastStr charLength];
            weiboLength = charLength2WeiboLength(charLength);
        }
        
        return mutableStr;
    }
}

-  (NSUInteger)charNumber:(NSString*)strtemp {
    
    NSUInteger strlength = 0;
    
    char* p = (char*)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding];
    
    for (NSUInteger i=0 ; i<[strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {
        
        if (*p) {
            p++;
            strlength++;
        } else {
            p++;
        }
        
    }
    
    return strlength;
}

@end
